package servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import triple.Triple;
import triple.node.Node;
import triple.node.NodeFactory;

/**
 * 完成的servlet
 * @author Da Huang (dhuang.cn@gmail.com)
 *
 */
public class Finish extends HttpServlet {

	private static final long serialVersionUID = -2891745714410883567L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
//		@SuppressWarnings("unchecked")
//		ArrayList<Entry<String, String>> trunks = (ArrayList<Entry<String, String>>) session.getAttribute("trunks");
		ArrayList<Triple> triples = new ArrayList<Triple>();
		int numOfTriples = Integer.parseInt(req.getParameter("numOfTriples"));
//		System.out.println(numOfTriples);
//		String type = new String(req.getParameter("triple-" + 0 + "-subject-type").getBytes("ISO8859-1"), "UTF-8");
//		String alias = new String(req.getParameter("triple-" + 0 + "-subject-alias").getBytes("ISO8859-1"), "UTF-8");
//		System.out.println(type + " " + alias);
		for (int i = 0; i < numOfTriples; i ++) {
			String type, entryIndex, alias;
			
			type = new String(req.getParameter("triple-" + i + "-subject-type").getBytes("ISO8859-1"), "UTF-8");
			entryIndex = new String(req.getParameter("triple-" + i + "-subject-entryIndex").getBytes("ISO8859-1"), "UTF-8");
			alias = new String(req.getParameter("triple-" + i + "-subject-alias").getBytes("ISO8859-1"), "UTF-8");
			Node subject = NodeFactory.getInstance().createNode(type, entryIndex, alias);

			type = new String(req.getParameter("triple-" + i + "-predicate-type").getBytes("ISO8859-1"), "UTF-8");
			entryIndex = new String(req.getParameter("triple-" + i + "-predicate-entryIndex").getBytes("ISO8859-1"), "UTF-8");
			alias = new String(req.getParameter("triple-" + i + "-predicate-alias").getBytes("ISO8859-1"), "UTF-8");
			Node predicate = NodeFactory.getInstance().createNode(type, entryIndex, alias);
			
			type = new String(req.getParameter("triple-" + i + "-object-type").getBytes("ISO8859-1"), "UTF-8");
			entryIndex = new String(req.getParameter("triple-" + i + "-object-entryIndex").getBytes("ISO8859-1"), "UTF-8");
			alias = new String(req.getParameter("triple-" + i + "-object-alias").getBytes("ISO8859-1"), "UTF-8");
			Node object = NodeFactory.getInstance().createNode(type, entryIndex, alias);
			
			triples.add(new Triple(subject, predicate, object));
		}
//		for (Triple triple : triples) {
//			System.out.println(triple);
//		}
		session.setAttribute("triples", triples);
		
		req.getRequestDispatcher("index5.jsp").forward(req, resp);
	}
}
